package com.gamejframe;

import com.gameluncher.UserLoginInfo;
import com.dao.RSMySQLData;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;

public class StoneJFrame extends JFrame implements KeyListener {
    int[][] datas = new int[4][4];
    int[][] victory = {{1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12},
            {13, 14, 15, 0}};
    //记录步数  放置图片坐标
    int step = 0, x0 = 0, y0 = 0;

    public StoneJFrame() {
        initJFrame();
        initMenu();
        initData();
        initImage();
        this.setVisible(true);
    }

    //初始化窗体
    public void initJFrame() {
        this.setSize(514, 595);
        this.setLocationRelativeTo(null);   //窗口居中
        this.setAlwaysOnTop(true);
        this.setTitle("石头迷阵");
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // 设置窗体关闭时的操作为释放资源
        this.addKeyListener(this);
        this.setLayout(null);
    }

    public void initMenu() {
        //创建菜单对象
        JMenuBar jMenuBar;
        jMenuBar = new JMenuBar();
        //设置菜单宽高
        jMenuBar.setSize(514, 20);

        //创建 重开 排名 暂停 继续
        JMenuItem restart, ranking, pause, proceed;

        restart = new JMenuItem("重新开始");
        restart.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //重新游戏，把图片随机排列，步数清零，计时清零
                initData();
                step = 0;
                initImage();
            }
        });
        //把选项放到菜单里
        jMenuBar.add(restart);

        ranking = new JMenuItem("排名");
        ranking.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                rankingList();
            }
        });
        jMenuBar.add(ranking);

        /*pause = new JMenuItem("暂停");
        pause.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //暂停游戏 停止按钮操控

            }
        });
        jMenuBar.add(pause);*/

        proceed = new JMenuItem("继续");
        proceed.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                initImage();
            }
        });
        jMenuBar.add(proceed);

        //把菜单放到窗体里
        this.setJMenuBar(jMenuBar);
    }

    public void initImage() {
        this.getContentPane().removeAll();
        JLabel label_step = new JLabel("步数" + step);
        label_step.setBounds(50, 20, 100, 20);
        this.add(label_step);

        if (victory()) {
            ImageIcon img = new ImageIcon("src/images/win.png");
            JLabel jLabel = new JLabel(img);
            jLabel.setBounds(514 / 2 - 266 / 2, 230, 266, 88);
            this.add(jLabel);
            int score = integralRule();
            RSMySQLData.updateScore(UserLoginInfo.getId(), score);
        }

        for (int i = 0; i < datas.length; i++) {
            for (int j = 0; j < datas[i].length; j++) {
                int data = datas[i][j];
                if (data != 0) {
                    ImageIcon imageIcon = new ImageIcon("src/images/" + data + ".png");
                    JLabel jLabel = new JLabel(imageIcon);
                    jLabel.setBounds(j * 100 + 50, i * 100 + 90, 100, 100);
                    this.add(jLabel);
                }
            }
        }
        ImageIcon bg = new ImageIcon("src/images/background.png");
        JLabel bgJLabel = new JLabel(bg);
        bgJLabel.setBounds(26, 30, 450, 484);
        this.add(bgJLabel);
        // 将整个界面重新绘制
        this.getContentPane().repaint();
    }

    public void initData() {
        int[] temp = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
        for (int i = 0; i < temp.length; i++) {
            Random r = new Random();
            //因为temp的长度为16，而.nextInt（temp.length）方法的意思是生成范围为[0,16)的随机数
            int index = r.nextInt(temp.length);
            int num = temp[i];
            temp[i] = temp[index];
            temp[index] = num;
        }
        for (int i = 0; i < temp.length; i++) {
            datas[i / 4][i % 4] = temp[i];
            if (temp[i] == 0) {
                x0 = i / 4;
                y0 = i % 4;
            }
        }
    }

    public boolean victory() {
        for (int i = 0; i < datas.length; i++) {
            for (int j = 0; j < datas[i].length; j++) {
                if (datas[i][j] != victory[i][j]) {
                    return false;
                }
            }
        }
        return true;
    }

    public void move(int keyCode) {
        // 左 || A
        if (keyCode == 37 || keyCode == 65) {
            if (y0 < 3) {
                datas[x0][y0] = datas[x0][y0 + 1];
                datas[x0][y0 + 1] = 0;
                y0++;
                step++;
            }
        }
        // 上 || W
        if (keyCode == 38 || keyCode == 87) {
            if (x0 < 3) {
                datas[x0][y0] = datas[x0 + 1][y0];
                datas[x0 + 1][y0] = 0;
                x0++;
                step++;
            }
        }
        // 右 || D
        if (keyCode == 39 || keyCode == 68) {
            if (y0 > 0) {
                datas[x0][y0] = datas[x0][y0 - 1];
                datas[x0][y0 - 1] = 0;
                y0--;
                step++;
            }
        }
        // 下 || S
        if (keyCode == 40 || keyCode == 83) {
            if (x0 > 0) {
                datas[x0][y0] = datas[x0 - 1][y0];
                datas[x0 - 1][y0] = 0;
                x0--;
                step++;
            }
        }
        // enter
        if (keyCode == 10) {
            datas = new int[][]{{1, 2, 3, 4},
                    {5, 6, 7, 8},
                    {9, 10, 11, 12},
                    {13, 14, 15, 0}};
        }
    }

    public void rankingList() {
        DefaultTableModel tableModel = RSMySQLData.selectGameScroe();
        if (tableModel != null){
            this.getContentPane().removeAll();
            // 创建JTable并设置数据模型
            JTable table = new JTable(tableModel);

            // 创建默认的单元格渲染器
            DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
            // 设置单元格内容居中对齐
            renderer.setHorizontalAlignment(SwingConstants.CENTER);

            // 遍历表格的列，将渲染器应用到每一列
            for (int i = 0; i < table.getColumnCount(); i++) {
                table.getColumnModel().getColumn(i).setCellRenderer(renderer);
            }

            // 创建滚动面板，并将JTable添加到其中
            JScrollPane scrollPane = new JScrollPane(table);
            scrollPane.setBounds(26, 30, 450, 484);
            // 将滚动面板添加到窗口中
            this.add(scrollPane);

            // 重新布局和绘制窗口
            this.revalidate();
            this.repaint();
            // 设置要高亮显示的行索引
            int rowIndex = RSMySQLData.selectGameScroe(UserLoginInfo.getUserPhone()) - 1; // （索引从0开始）
            table.setRowSelectionInterval(rowIndex, rowIndex);
        }

    }

    public int integralRule() {
        int integral = 0;
        if(step > 0) {
            integral = 50000 / step;
        }
        return integral;
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {

    }

    @Override
    public void keyReleased(KeyEvent e) {
        int keyCode = e.getKeyCode();
        //System.out.println(keyCode);
        move(keyCode);
        //重新绘制界面
        initImage();
    }
}